package com.coder.shop.web.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.coder.shop.dao.model.ShopGoodsSku;
import com.coder.shop.dao.model.ShopGoodsType;
import com.coder.shop.rpc.api.ShopGoodsSkuService;
import com.coder.shop.rpc.api.ShopGoodsTypeService;

@Controller
public class TtemCategoryController {
	
	@Resource
	private ShopGoodsTypeService shopGoodsTypeService;
	
	@Resource
	private ShopGoodsSkuService shopGoodsSkuService;

	/**
	 * 
	 * @param map
	 * @param typeId
	 * @param specValues  使用逗号分隔所有的值，specId1_value2,specId2_value1
	 * @return
	 */
	@RequestMapping("item_category")
	public String itemCategory(ModelMap map,Integer typeId,String specValues,Double startPrice,Double endPrice,@RequestParam(required=false,defaultValue="1")Integer pageIndex,@RequestParam(required=false,defaultValue="20")Integer pageSize,String orderColum,String sort) {
		
		//排序
		map.put("orderColum", orderColum);
		map.put("sort", sort);
		if(StringUtils.isNotBlank(orderColum)) {
			if("price".equals(orderColum)) {
				orderColum = "sku.price";
			}
			if(StringUtils.isBlank(sort)) {
				sort = "desc";
			}
		}
		
		List<ShopGoodsType> typelist = shopGoodsTypeService.findTreeList();
		
		List<ShopGoodsType> checkedTypes = new ArrayList<ShopGoodsType>();
		
		List<List<ShopGoodsType>> levelTypeList = new ArrayList<List<ShopGoodsType>>();
		
		List<ShopGoodsType> topTypes = new ArrayList<>();
		levelTypeList.add(topTypes);
		
		for (ShopGoodsType type : typelist) {
			topTypes.add(type);
			if(typeId!=null) {
				if(type.getId().intValue() == typeId.intValue()) {
					checkedTypes.add(0, type);
				}else {
					if(findChild(type,typeId,checkedTypes)) {
						checkedTypes.add(0, type);
					}
				}
			}
		}
		
		List<ShopGoodsType> next = topTypes;
		do {
			next = findNextPage(next);
			if(next!=null && next.size()>0) {
				levelTypeList.add(next);
			}
		}while(next!=null && next.size()>0);
				
		map.put("typeId", typeId);
		map.put("checkedIds", checkedTypes);
		for(int i = checkedTypes.size()-1;i>0;i--) {
			ShopGoodsType type = checkedTypes.get(i);
			if(type.getShopSpecList()!=null && type.getShopSpecList().size()>0) {
				map.put("specs", type.getShopSpecList());
				break;
			}
		}
		
		String[] specsValue = null;
		if(StringUtils.isNotBlank(specValues)) {
			Map<String,String> speValueMap = new HashMap<String, String>();
			String[] specs = specValues.split(",");
			ArrayList<String> specsValueList = new ArrayList<String>(specs.length);
			for(String item : specs) {
				String[] spv = item.split("_");
				if(spv.length==2) {
					speValueMap.put(spv[0], spv[1]);
					specsValueList.add(spv[1]);
				}
			}
			//Arrays.copyOf(specsValueList.toArray(), specsValueList.size(), String[].class);
			specsValue = new String[specsValueList.size()];
			for(int i = 0;i<specsValueList.size();i++) {
				specsValue[i]=specsValueList.get(i);
			}
			map.put("checkedSpecValue", speValueMap);
		}
		
		map.put("typelist", typelist);
		
		Integer startPage = (pageIndex-1) * pageSize;
		
		//查询商品
		List<ShopGoodsSku> categoryGoods = shopGoodsSkuService.categoryGoods(typeId, specsValue, startPrice==null?null:new BigDecimal(startPrice), endPrice==null?null:new BigDecimal(endPrice), startPage, pageSize, orderColum, sort);
		map.put("categoryGoods", categoryGoods);
		Integer count = shopGoodsSkuService.categoryGoodsCount(typeId, specsValue, startPrice==null?null:new BigDecimal(startPrice), endPrice==null?null:new BigDecimal(endPrice));
		
		int total = count / pageSize + count%pageSize==0?0:1;
		map.put("total", total);
		map.put("pageIndex", pageIndex);
		
		
		return "item_category";
	}
	
	public List<ShopGoodsType> findNextPage(List<ShopGoodsType> currentTypes){
		List<ShopGoodsType> types = new ArrayList<>();
		for (ShopGoodsType type : currentTypes) {
			types.addAll(type.getChildren());
		}
		return types;
	}
	
	/**
	 * 查找树形结构的子节点
	 * @param type
	 * @param typeId
	 * @return
	 */
	private boolean findChild(ShopGoodsType type,Integer typeId,List<ShopGoodsType> checkedIds) {
		List<ShopGoodsType> children = type.getChildren();
		if(children == null || children.size()==0 ) {
			return false;
		}
		for (ShopGoodsType item : children) {
			if(item.getId().intValue() == typeId.intValue()) {
				checkedIds.add(0, item);
				return true;
			}else {
				if(findChild(item,typeId,checkedIds)) {
					checkedIds.add(0, item);
					return true;
				}
			}
		}
		return false;
	}
	
}
